<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="8">
        <el-card header="设备状况" >
          <div style="display: flex">
            <chart v-if="devOnlineData.length > 0" id="left" :chart-data="devOnlineData"/>
            <div class="onlineInfoBox">
              <div style="width: 50%" v-for="item in devOnlineData">
                <p>{{item.name}}</p>
                <span :style="item.name === '在线' ? {color: '#1ab394'}:{color: '#ed5565'}">{{ item.value }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card header="关联用户">
          <div style="height: 150px">
            <div class="deviceListHomepageBoxUsersBelongBox">
              <ul>
                <li v-for="item in BelongUsers" :key="item">
                  <p>{{item.name}}</p>
                  <p class="fontColor" style="color: #f60">{{item.num}}</p>
                </li>
              </ul>
            </div>
            <!-- 分页器 -->
            <el-pagination
                layout="prev, pager, next"
                :total="totalRelateUser"
                :pager-count="4"
                :current-page="relateUser.currentPage"
                :page-size="relateUser.pageSize"
                @current-change="handleCurrentChangeRelateUser"
                background
                :small="true"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card header="今日报警">
          <div style="display: flex">
          <chart v-if="devWarnData.length > 0" id="right" :chart-data="devWarnData"/>
          <div class="onlineInfoBox">
            <div style="width: 50%">
              <p>未处理</p>
              <span style="color: #ed5565">{{todayAlarmData}}</span>
            </div>
            <div style="width: 50%">
              <p>已处理</p>
              <span style="color: #1ab394">0</span>
            </div>
          </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="number">
        <el-input
            v-model="queryParams.number"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择设备类型" clearable>
          <el-option
              v-for="dict in dicts.device_cut_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通讯设备" prop="equipment">
        <el-select v-model="queryParams.equipment" placeholder="请选择通讯设备" clearable>
          <el-option
              v-for="dict in dicts.equipment_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属项目" prop="project">
        <el-select v-model="queryParams.project" placeholder="请选择所属项目" clearable>
          <el-option
              v-for="dict in dicts.device_project_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option
              v-for="dict in dicts.device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['business:device:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:device:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:device:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:device:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="设备名称" align="center" prop="name"/>
      <el-table-column label="设备编号" align="center" prop="number"/>
      <el-table-column label="设备类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="dicts.device_cut_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="通讯设备" align="center" prop="equipment">
        <template #default="scope">
          <dict-tag :options="dicts.equipment_type" :value="scope.row.equipment"/>
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="project">
        <template #default="scope">
          <dict-tag :options="dicts.device_project_type" :value="scope.row.project"/>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dicts.device_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="设备图片" align="center" prop="pic">
          <template #default="scope">
            <el-image style="width: 50px; height: 50px" :src="scope.row.pic" fit="contain" />
          </template>
      </el-table-column>
      <el-table-column label="设备地址" align="center" prop="address"/>
      <el-table-column label="工作班次" align="center" prop="workTimes">
        <template #default="scope">
          <dict-tag :options="dicts.work_times_type" :value="scope.row.workTimes"/>
        </template>
      </el-table-column>
      <el-table-column label="最后在线时间" align="center" prop="lastOnline" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastOnline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding">
        <template #default="scope">
          <el-button
              size="mini"
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:device:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:device:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
<!--        <el-form-item label="所属部门" prop="parentId">-->
<!--          <el-tree-select-->
<!--              v-model="form.deptId"-->
<!--              :data="deptOptions"-->
<!--              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"-->
<!--              value-key="deptId"-->
<!--              placeholder="选择上级部门"-->
<!--              check-strictly-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="所属项目" prop="project">
          <el-select v-model="form.project" placeholder="请选择所属项目" @change="(value)=>{projectType = value}">
            <el-option
                v-for="dict in dicts.device_project_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="设备编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入设备编号"/>
        </el-form-item>
        <el-form-item label="归属工厂" prop="deptId">
          <el-tree-select
              v-model="form.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属工厂"
              check-strictly
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
                v-if="projectType == 1"
                v-for="dict in dicts.device_cut_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
            <el-radio
                v-else
                v-for="dict in dicts.device_robot_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通讯设备" prop="equipment">
          <el-radio-group v-model="form.equipment">
            <el-radio
                v-for="dict in dicts.equipment_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in dicts.device_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备图片" prop="pic">
<!--          <el-input v-model="form.pic" placeholder="请输入设备图片"/>-->
          <el-upload
              action="/dev-api/business/device/upload/devicePic"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :headers="headers"
              drag
              list-type="picture"
              :limit="1"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="工作班次" prop="workTimes">
          <el-select v-model="form.workTimes" placeholder="请选择工作班次">
            <el-option
                v-for="dict in dicts.work_times_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首班次工作开始时间" prop="beginTime">
          <el-time-picker clearable
                          v-model="form.beginTime"
                          type="datetime"
                          format="HH:mm:ss"
                          value-format="HH:mm:ss"
                          placeholder="请选择首班次工作开始时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item v-if="form.workTimes > 1" label="首班次工作时长" prop="durationH">
          <el-input v-model="form.durationH" placeholder="请输入首班次工作时长(小时)"/>
        </el-form-item>
        <el-form-item v-if="form.workTimes > 1" label="首班次工作时长" prop="durationM">
          <el-input v-model="form.durationM" placeholder="请输入首班次工作时长(分钟)"/>
        </el-form-item>
        <el-form-item v-if="form.workTimes > 2" label="第二班次工作时长" prop="durationH">
          <el-input v-model="form.secondDurationH" placeholder="请输入第二班次工作时长(小时)"/>
        </el-form-item>
        <el-form-item v-if="form.workTimes > 2" label="第二班次工作时长" prop="durationM">
          <el-input v-model="form.secondDurationM" placeholder="请输入第二班次工作时长(分钟)"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="设备地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入设备地址" @change="onInput"/>
        </el-form-item>
      </el-form>
      <BMap height="300px" ref="map"
            :enableScrollWheelZoom="true"
            :center="point" @initd="handleInitd" @click="handleClick"
      >
<!--        <BAutoComplete style="width: 100%;z-index: 999" @confirm="handleConfirm" />-->
        <BMarker :position="point"></BMarker>
        <!--        <BLabel-->
        <!--            style="color: #333; font-size: 9px"-->
        <!--            :position="result.point"-->
        <!--            :content="`地址: ${result?.address} 所属商圈:${result?.business} 最匹配地点: ${-->
        <!--            result?.surroundingPois[0]?.title || '无'-->
        <!--          }`"-->
        <!--        />-->
        <!-- ... -->
      </BMap>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  statisticsDevOnline,
  statisticsRelateUser
} from "@/api/device";
import {getCurrentInstance} from "vue";
import {BMap, BZoom, BLabel,BAutoComplete, usePointGeocoder, useAddressGeocoder} from 'vue3-baidu-map-gl'
import {ElMessageBox} from "element-plus";
import {deptTreeSelect} from "@/api/system/user";
import { getToken } from '@/utils/auth'
import Chart from './chart'
import {listDept} from "../../api/system/dept";
import {statisticsTodayAlarm} from "../../api/device";
// const { proxy } = getCurrentInstance();
// const { device_cut_type,device_status,equipment_type,work_times_type,device_project_type }
//     = proxy.useDict("device_cut_type","device_status","equipment_type","work_times_type","device_project_type");
//const { get, result, isLoading, isEmpty } = usePointGeocoder()
const {get, point, isLoading, isEmpty} = useAddressGeocoder(() => {
  map.value.resetCenter()
})

export default {
  name: "Device",
  components: {
    BMap,
    BZoom,
    BLabel,
    Chart,
    BAutoComplete
  },
  //dicts: ['device_cut_type', 'device_status', 'equipment_type', 'work_times_type', 'device_project_type'],
  data() {
    return {
      center: '浙江省',
      zoom: 3,
      //所属项目类型
      projectType:1,
      //字典
      dicts: {},
      chartDataLeft: [
        { name: '状态1', value: 30 },
        { name: '状态2', value: 70 }
      ],
      useAddressGeocoder: null,
      //地图坐标点
      point: {lng: 116.30793520652882, lat: 40.05861561613348},
      //部门选项
      deptOptions: null,
      //文件上传请求头
      headers:{},
      //设备在线统计数据
      devOnlineData:[],
      //设备今日报警数据
      todayAlarmData:0,
      //设备报警统计数据
      devWarnData:[],
      //关联用户统计数据
      BelongUsers:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        name: null,
        number: null,
        type: null,
        equipment: null,
        project: null,
        status: null,
        pic: null,
        address: null,
        coordinateLon: null,
        coordinateLat: null,
        workTimes: null,
        durationH: null,
        durationM: null,
        beginTime: null,
        endTime: null,
        lastOnline: null,
      },
      //关联用户分页
      relateUser:{
        currentPage: 1,
        pageSize: 9,
      },
      //关联用户总条数
      totalRelateUser:0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [
          {required: true, message: "工厂不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        number: [
          {required: true, message: "设备编号不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "请选择设备类型", trigger: "blur"}
        ],
        equipment: [
          {required: true, message: "请选择通讯设备", trigger: "blur"}
        ],
        status: [
          {required: true, message: "请选择设备状态", trigger: "blur"}
        ],
        address: [
          {required: true, message: "请输入设备地址", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    const { proxy } = getCurrentInstance();
    this.getList();
    this.dicts = proxy.useDict("device_cut_type", "device_status", "equipment_type", "work_times_type", "device_project_type","device_robot_type");
    this.statisticsDevOnline()
  },
  mounted() {
    this.getDeptTree()
    this.useAddressGeocoder = useAddressGeocoder(() => {
      this.$refs.map.resetCenter()
    })
    this.statisticsDevOnline()
    this.statisticsRelateUser()
    this.statisticsTodayAlarm()
  },
  methods: {
    //处理关联用户分页
    handleCurrentChangeRelateUser(pageNum){
      this.relateUser.currentPage = pageNum
      this.statisticsRelateUser()
    },
    handleSuccess(response, file, fileList) {
      this.form.pic = response.data
      this.$message.success("上传成功");
    },
    handleConfirm(e) {
      const value = e.item.value
      get(value.city || value.business, value.province + value.city + value.district + value.street + value.business)
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt5M = file.size / 1024 < 5000;

      if (!isJPG) {
        this.$message.error("只能上传jpg/png文件");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("文件大小不能超过500kb");
        return false;
      }
      this.headers['Authorization'] = getToken();
      return true;
    },
    handler({BMap, map}) {
      this.center.lng = 116.404
      this.center.lat = 39.915
      this.zoom = 15
    },
    handleInitd() {
      get(this.point)
    },
    onInput(value) {
      this.point = value
      this.$nextTick(() => {
        this.$refs.map.resetCenter()
        this.point = {lng: this.useAddressGeocoder.point.lng, lat: this.useAddressGeocoder.point.lat}

      })
    },
    handleClick(e) {
      this.form.coordinateLon = e.latlng.lng
      this.form.coordinateLat = e.latlng.lat
      this.point = e.latlng
      this.useAddressGeocoder.get(e.latlng)
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        name: null,
        number: null,
        type: null,
        equipment: null,
        project: null,
        status: null,
        pic: null,
        address: null,
        coordinateLon: null,
        coordinateLat: null,
        workTimes: null,
        durationH: null,
        durationM: null,
        secondDurationH: null,
        secondDurationM: null,
        beginTime: null,
        endTime: null,
        lastOnline: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 统计设备在线状况信息 */
    statisticsDevOnline(){
      statisticsDevOnline().then((res)=>{
        this.devOnlineData = res.data.map((item)=>{
          return {
            value: item.value,
            name: item.status === true ? '在线' : '离线',
          }
        })
      })
    },
    /** 统计设备今日报警 */
    statisticsTodayAlarm(){
      statisticsTodayAlarm().then((res)=>{
        this.todayAlarmData = res.data.count
        this.devWarnData.push({
          name:'报警',
          value: res.data.count,
          itemStyle: {
            color: '#fa5f5f'
          }
        })
        this.devWarnData.push({
          name:'已处理',
          value: 0,
          itemStyle: {
            color: '#7ab042'
          }
        })
      })
    },
    /** 统计设备报警状况信息 */
    statisticsDevWarn(){

    },
    /** 统计关联用户信息 */
    statisticsRelateUser(){
      statisticsRelateUser(this.relateUser).then((res)=>{
        this.BelongUsers = res.rows
        this.totalRelateUser = res.total
      })


    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      //this.$router.push('/device/add')
      this.open = true;
      this.reset();
      this.getDeptTree()
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.point = {lng: this.form.coordinateLon, lat: this.form.coordinateLat}
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.coordinateLat == null || this.form.coordinateLon == null) {
        ElMessageBox.alert("请在地图中标记准确位置");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + ids + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.onlineInfoBox{
  text-align: center;
  font-size: 14px;
  width: 50%;
  display: flex;
  flex-wrap: wrap;
}
.deviceListHomepageBoxUsersBelongBox{
  box-sizing: border-box;
  height: 126px;
}
.deviceListHomepageBoxUsersBelongBox ul{
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  overflow: hidden;
}
.deviceListHomepageBoxUsersBelongBox li{
  list-style: none;
  width: 30%;
}
.deviceListHomepageBoxUsersBelongBox li p{
  margin: 0;
  line-height: 21px;
  text-align: center;
  font-size: 14px;
}
</style>
